<?
require_once(dirname(__FILE__) . '/../../classes/report_interface.inc.php');
require_once(dirname(__FILE__) . '/../../classes/graph.inc.php');

abstract class LoggerModuleDayReportBaseClass 
{
    protected $database;

    public function __construct(LoggerDatabase $database) 
    {
        $this->database = $database;
    }

    public function GetData($date1, $date2, $hour = false)
    {
        $date1 = '\'' . mysql_escape_string($date1) . '\'';
        $date2 = '\'' . mysql_escape_string($date2) . '\'';

        $hourWhere = '';
        if ($hour !== false)
            $hourWhere = ' AND `hour`=' . intval($hour) . ' ';
    
        $SelectSQL = 'SELECT SUM(`count`) AS `count`, SUM(`sessions`) AS `sessions`, SUM(`visitors`) AS `visitors` ';
        $SelectSQL .= 'FROM `[PREF]module_dayrw_archive` WHERE `date`>='.$date1.' AND `date`<='.$date2.' '.$hourWhere;
        
        $result = $this->database->Query($SelectSQL);
        if (!$result)
            trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
        $row = $this->database->FetchAssoc($result);
        $this->database->FreeResult($result);
        $hits           = intval($row['count']);
        $sessions       = intval($row['sessions']);
        $visitors       = intval($row['visitors']);

        return array(
            'hits'          => $hits,
            'sessions'      => $sessions,
            'visitors'      => $visitors,
            'visitorsNew'   => 0
        );
    }
}

class LoggerModuleDayMainReport extends LoggerModuleDayReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'Статистика посещений');
        $root->appendChild($name);

        $data = $this->GetData($date1, $date2);
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);
        $reportData->setAttribute('hits', $data['hits']);
        $reportData->setAttribute('sessions', $data['sessions']);
        $reportData->setAttribute('visitors', $data['visitors']);

        $xsl = dirname(__FILE__) . '/templates/main.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);

        return true;
    }
}

class LoggerModuleDayByDateReport extends LoggerModuleDayReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'Статистика посещений');
        $root->appendChild($name);

        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);
        $data = $this->GetData($date1, $date2);
        $dataRow = $xml->createElement('row');
        $reportData->appendChild($dataRow);
        $dataRow->setAttribute('dateHuman', 'Всего');
        $dataRow->setAttribute('hits', $data['hits']);
        $dataRow->setAttribute('sessions', $data['sessions']);
        $dataRow->setAttribute('visitors', $data['visitors']);
        
        $timeStamp = strtotime($date1);
        $timeStop = strtotime($date2);
        while($timeStamp <= $timeStop)
        {
            $date = date('Y-m-d', $timeStamp);
            $data = $this->GetData($date, $date);
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            $dataRow->setAttribute('date', $date);
            $dataRow->setAttribute('dateHuman', date('d.m.Y', $timeStamp));
            $dataRow->setAttribute('hits', $data['hits']);
            $dataRow->setAttribute('sessions', $data['sessions']);
            $dataRow->setAttribute('visitors', $data['visitors']);
            $timeStamp = strtotime('+1 day', $timeStamp);
        }

        $xsl = dirname(__FILE__) . '/templates/by_date.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}


class LoggerModuleDayGraphHoursReport extends LoggerModuleDayReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'График посещений по часам');
        $root->appendChild($name);
        
        $graphData = array(
            'legend' => array(
                'hits' => 'Хитов',
                'sessions' => 'Посещений',
                'visitors' => 'Посетителей'
            ),
            'colors' => array(
                'hits' => '#6495ED',
                'sessions' => '#8FBC8F',
                'visitors' => '#FF6347'
            ),
            'data' => array()
        );
        
        for ($h=0; $h<24; $h++)
        {
            $data = $this->GetData($date1, $date2, $h);
            $graphData['data'][$h] = array(
                'values' => array(
                    'hits' => $data['hits'],
                    'sessions' => $data['sessions'],
                    'visitors' => $data['visitors']
                ),
                'attributes' => array(
                )
            );
        }
    
        LoggerBarGraph::BuildGraph($root, $graphData);

        $xsl = dirname(__FILE__) . '/templates/graph_hours.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);

        return true;
    }
}

class LoggerModuleDayGraphDaysReport extends LoggerModuleDayReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $arDaysOfTheWeek = array(
            0 => 'Вс',
            1 => 'Пн',
            2 => 'Вт',
            3 => 'Ср',
            4 => 'Чт',
            5 => 'Пт',
            6 => 'Сб'
        );

        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'График посещений по дням');
        $root->appendChild($name);

        $graphData = array(
            'legend' => array(
                'hits' => 'Хитов',
                'sessions' => 'Посещений',
                'visitors' => 'Посетителей'
            ),
            'colors' => array(
                'hits' => '#6495ED',
                'sessions' => '#8FBC8F',
                'visitors' => '#FF6347'
            ),
            'data' => array()
        );

        $timeStamp = strtotime($date1);
        $timeStop = strtotime($date2);
        while($timeStamp <= $timeStop)
        {
            $date = date('Y-m-d', $timeStamp);
            $dateHuman = date('d.m.Y', $timeStamp);
            $dayOfWeek = date('w', $timeStamp);
            $dateHuman = $arDaysOfTheWeek[$dayOfWeek] . ',&#160;'. $dateHuman;
            $theOffDay = $dayOfWeek == 0 || $dayOfWeek == 6;
            $data = $this->GetData($date, $date);
            $graphData['data'][$dateHuman] = array(
                'values' => array(
                    'hits' => $data['hits'],
                    'sessions' => $data['sessions'],
                    'visitors' => $data['visitors']
                ),
                'attributes' => array(
                    'date' => $date,
                    'day' => $theOffDay ? 'off' : ''
                )
            );
            $timeStamp = strtotime('+1 day', $timeStamp);
        }
        
        LoggerBarGraph::BuildGraph($root, $graphData);

        $xsl = dirname(__FILE__) . '/templates/graph_days.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);

        return true;
    }
}

class LoggerModuleDayGraphWeeksReport extends LoggerModuleDayReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'График посещений по неделям');
        $root->appendChild($name);
        
        $graphData = array(
            'legend' => array(
                'hits' => 'Хитов',
                'sessions' => 'Посещений',
                'visitors' => 'Посетителей'
            ),
            'colors' => array(
                'hits' => '#6495ED',
                'sessions' => '#8FBC8F',
                'visitors' => '#FF6347'
            ),
            'data' => array()
        );

        $timeStamp = strtotime($date1);
        if (date('w', $timeStamp) != '1')
            $timeStamp = strtotime('last Monday', $timeStamp);
        $timeStop = strtotime($date2);
        if (date('w', $timeStop) != '0')
            $timeStop = strtotime('next Sunday', $timeStop);
        while($timeStamp <= $timeStop)
        {
            $timeStampInterval1 = $timeStamp;
            $timeStampInterval2 = strtotime('+6 day', $timeStamp);
            
            $dateInterval1 = date('Y-m-d', $timeStampInterval1);
            $dateInterval1Human = date('d.m.Y', $timeStampInterval1);
            $dateInterval2 = date('Y-m-d', $timeStampInterval2);
            $dateInterval2Human = date('d.m.Y', $timeStampInterval2);
            $data = $this->GetData($dateInterval1, $dateInterval2);
            $graphData['data'][$dateInterval1Human . '&#160;...&#160;' . $dateInterval2Human] = array(
                'values' => array(
                    'hits' => $data['hits'],
                    'sessions' => $data['sessions'],
                    'visitors' => $data['visitors']
                ),
                'attributes' => array(
                    'date1' => $dateInterval1,
                    'date2' => $dateInterval2
                )
            );
            $timeStamp = strtotime('+7 day', $timeStamp);
        }
        
        LoggerBarGraph::BuildGraph($root, $graphData);

        $xsl = dirname(__FILE__) . '/templates/graph_weeks.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);

        return true;
    }
}

class LoggerModuleDayGraphMonthsReport extends LoggerModuleDayReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $arMonths = array(
            1 => 'Январь',
            2 => 'Февраль',
            3 => 'Март',
            4 => 'Апрель',
            5 => 'Май',
            6 => 'Июнь',
            7 => 'Июль',
            8 => 'Август',
            9 => 'Сентябрь',
            10 => 'Октябрь',
            11 => 'Ноябрь',
            12 => 'Декабрь'
        );
        $xml = $root->ownerDocument;

        $name = $xml->createElement('report_name', 'График посещений по месяцам');
        $root->appendChild($name);
        
        $graphData = array(
            'legend' => array(
                'hits' => 'Хитов',
                'sessions' => 'Посещений',
                'visitors' => 'Посетителей'
            ),
            'colors' => array(
                'hits' => '#6495ED',
                'sessions' => '#8FBC8F',
                'visitors' => '#FF6347'
            ),
            'data' => array()
        );

        $timeStamp = strtotime(date('Y-m-1', strtotime($date1)));
        $timeStop = strtotime(date('Y-m-t', strtotime($date2)));

        while($timeStamp <= $timeStop)
        {
            $dateInterval1 = date('Y-m-d', $timeStamp);
            $dateInterval2 = date('Y-m-t', $timeStamp);
            $monthNum = date('n', $timeStamp);
            $yearNum = date('Y', $timeStamp);
            $data = $this->GetData($dateInterval1, $dateInterval2);
            $graphData['data'][$arMonths[$monthNum] . '&#160;' . $yearNum] = array(
                'values' => array(
                    'hits' => $data['hits'],
                    'sessions' => $data['sessions'],
                    'visitors' => $data['visitors']
                ),
                'attributes' => array(
                    'date1' => $dateInterval1,
                    'date2' => $dateInterval2
                )
            );
            $timeStamp = strtotime('+1 month', $timeStamp);
        }
        
        LoggerBarGraph::BuildGraph($root, $graphData);

        $xsl = dirname(__FILE__) . '/templates/graph_months.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);

        return true;
    }
}
